import Vue from 'vue'
import Vuex from 'vuex'
import {addressList, addressAdd} from '../request/api.js'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    userinfo:sessionStorage.getItem('userinfo')?JSON.parse(sessionStorage.getItem('userinfo')): null,
    addresslist: []
  },
  getters:{
    getUser(state){
      return state.userinfo
    },
    getAddressList(state) {
      return state.addresslist
    }
  },
  mutations: {
    CHANGE_USER(state,payload){
      state.userinfo = payload
      if(payload){
        // 把数据顺便存储到会话存储中
        sessionStorage.setItem('userinfo',JSON.stringify(payload))
      }else{
        //移除存储信息
        sessionStorage.removeItem('userinfo')
      }
    },
    CHANGE_ADDRESS(state, payload){
      state.addresslist = payload
    }
  },
  actions: {
    //封装一个修改state的行动
    changeUser({commit},payload){
      console.log('行动');
      commit('CHANGE_USER',payload)
    },
    getAddressAction(context){
      addressList({
        uid: context.state.userinfo.uid
      }).then(res => {
        if (res.data.code == 200) {
            let list = []
            let temp = res.data.list
            temp.map(item => {
              let {
                id,
                username:name,
                userphone:tel,
                location:province,
                useraddress:county,
                regioncode:areaCode,
                status:isDefault,
                city,
              } = item
              let i = { id,
                name,
                tel,
                addressDetail:county,
                address:province+county,
                isDefault:true,
                areaCode}
              list.push(i)
            })
          context.commit('CHANGE_ADDRESS', list)
        }
        console.log(context.getters.getAddressList)
    })
    }
  },
  modules: {
  }
})
